package com.ruoyi.crop.controller;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.crop.api.domain.City;
import com.ruoyi.crop.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.web.domain.AjaxResult.success;

@RestController
@RequestMapping("city")
public class CityController {
    @Autowired
    CityService cityService;
    @Autowired
    HttpServletResponse response;
    @Autowired
    RedisTemplate redisTemplate;


//    @RequestMapping("cityMenu")
//    public AjaxResult cityMenu(){
//        List<City>  nodeList = (List<City>) redisTemplate.opsForValue().get("cityList");
//        //配置
//        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
//        //转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
//        List<Tree<String>> treeNodes = TreeUtil.<City, String>build(nodeList, "1", treeNodeConfig,
//                (treeNode, tree) -> {
//                    tree.setId(treeNode.getCityId()+"");
//                    tree.setName(treeNode.getCityname());
//                    tree.setParentId(treeNode.getPid()+"");
//                });
//        return success(treeNodes);
//    }
    @PostConstruct
    public void init(){
        List<City> nodeList = cityService.list();
        redisTemplate.opsForValue().set("cityList",nodeList);
    }
    @RequestMapping("cityMenu")
    public AjaxResult cityMenu(){
        List<City>  list = (List<City>) redisTemplate.opsForValue().get("cityList");
        List<City> collect = list.stream().filter(city -> city.getPid() == 1).collect(Collectors.toList());
        streamToTree(collect,"0");
        return success(list);
    }

    public static List<City> streamToTree(List<City> treeList, String parentId) {
        List<City> list = treeList.stream()
                // 过滤父节点
                .filter(parent -> parent.getPid().equals(parentId))
                // 把父节点children递归赋值成为子节点
                .map(child -> {
                    child.setChildren(streamToTree(treeList,child.getCityId()+""));
                    return child;
                }).collect(Collectors.toList());
        return list;
    }



}
